package com.jt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {
    public static Object getProxy(Object target) {
        //获取加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //获取接口数组类型
        Class[] interfaces = target.getClass().getInterfaces();
        //代理对象执行方法时回调方法
        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler(target));


    }

    public static InvocationHandler invocationHandler(Object target) {
        return new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("事务开启");
                Object result = method.invoke(target, args);
                System.out.println("事务提交");
                return result;
            }
        };
    }

    public static Object getTimeProxy(Object target) {

        ClassLoader classLoader = target.getClass().getClassLoader();

        Class[] interfaces = target.getClass().getInterfaces();

        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandlerTime(target));
    }

    public static InvocationHandler invocationHandlerTime(Object target) {
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                long startTime = System.currentTimeMillis();
                Object result = method.invoke(target, args);
                long endTime = System.currentTimeMillis();
                System.out.println("耗时" + (endTime - startTime));
                return result;
            }
        };
    }
    public static Object getManProxy(Object target){
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class[] interfaces = target.getClass().getInterfaces();
        return Proxy.newProxyInstance(classLoader,interfaces,invocationHandlerman(target));
    }

    private static InvocationHandler invocationHandlerman(Object target) {
        return new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开始");
                Object result = method.invoke(target, args);
                System.out.println("结束");
                return result;
            }
        };
    }
}
